import jsonpath

from api.base_api import BaseApi


class GoodsApi(BaseApi):

    def add(self, goods_data):
        """添加商品"""
        url_add = "admin/goods/create"
        r_add = self.send_req("post", url_add, json=goods_data)
        return r_add

    def add_by_name(self, goods_name):
        """添加指定名称的商品"""
        goods_data = {
            "goods": {
                "picUrl": "",
                "gallery": [

                ],
                "isHot": True,
                "isNew": True,
                "isOnSale": True,
                "goodsSn": "12491264512421",
                "name": goods_name,
                "counterPrice": "8888"
            },
            "specifications": [
                {
                    "specification": "规格",
                    "value": "标准",
                    "picUrl": ""
                }
            ],
            "products": [
                {
                    "id": 0,
                    "specifications": [
                        "标准"
                    ],
                    "price": 0,
                    "number": 0,
                    "url": ""
                }
            ],
            "attributes": [
                {
                    "attribute": "材质",
                    "value": "纯棉"
                }
            ]
        }
        return self.add(goods_data)

    def search(self, params):
        """查询商品"""
        url_get = "admin/goods/list"
        r_search = self.send_req("get", url_get, params=params)
        return r_search

    def search_goodsname_exist(self, goods_name):
        """查询商品是否存在"""
        params = {'name': goods_name}
        r_search = self.search(params)
        res_name = jsonpath.jsonpath(r_search.json(), '$..name')
        return False if not res_name else True

    def get_goodsid_by_name(self, goods_name):
        """通过商品名称获取商品id"""
        params = {'name': goods_name}
        r_id = self.search(params)
        goods_id = jsonpath.jsonpath(r_id.json(), '$..id')[0]
        return goods_id

    def delete(self, goods_data):
        """删除商品"""
        url_delete = "admin/goods/delete"
        r_delete = self.send_req("post", url_delete, json=goods_data)
        return r_delete

    def delete_by_id(self, goods_id):
        """通过商品id删除商品"""
        goods_data = {'id': goods_id}
        return self.delete(goods_data)

    def delete_by_name(self, goods_name):
        """通过商品id删除商品"""
        goods_id = self.get_goodsid_by_name(goods_name)
        return self.delete_by_id(goods_id)
